﻿/*
 * Copyright © 2025−2026 WEI.ZHOU (Willis) (Chengdu). All rights reserved.
 *
 * THIS SOURCE CODE IS PROPRIETARY AND CONFIDENTIAL.
 * It is the exclusive property of WEI.ZHOU (Willis) and may not be
 * used, copied, distributed, or disclosed outside of WEI.ZHOU (Willis)
 * without express written permission.
 *
 * This code is provided to WEI.ZHOU (Willis) under a limited, 
 * non-transferable internal license, and is for use only with the author's 
 * approved purposes. No external license is granted or implied.
 *
 * Any unauthorized use, reproduction, or distribution is strictly prohibited
 * and may result in severe civil and criminal penalties.
 */

using Aore.Core.BaseModels.CdoBaseModel;
using Microsoft.EntityFrameworkCore;
using System.Reflection;

namespace Aore.Core.Repository.EFCore;

public class ApplicationDbContext : DbContext {

  /// <summary>
  /// 创建数据库上下文
  /// </summary>
  /// <param name="options"></param>
  public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
    : base(options) {

  }
  
  /// <summary>
  /// 模型创建
  /// </summary>
  /// <param name="modelBuilder"></param>
  protected override void OnModelCreating(ModelBuilder modelBuilder) {
    var definedTypes = new List<TypeInfo>();

    var assembies = AppDomain.CurrentDomain.GetAssemblies();
    foreach (var an in assembies) {
      var tempNameDataList = an.DefinedTypes.Where(x => x.BaseType == typeof(NameDataObject)).ToList();
      definedTypes.AddRange(tempNameDataList);
      
      var tempRevisionDataList = an.DefinedTypes.Where(x => x.BaseType == typeof(RevisionDataObject)).ToList();
      definedTypes.AddRange(tempRevisionDataList);
    }
            
    foreach (Type type in definedTypes) {
      if (type.IsClass && (type != typeof(NameDataObject) || type != typeof(RevisionDataObject))) {
                    
        modelBuilder.Entity(type);
        type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
          .ToList()
          .ForEach(p => {
            // Replace the problematic code block with the following:
            type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
              .ToList()
              .ForEach(p =>
              {
                modelBuilder.Entity(type).Property(p.Name);
              });
          });
      }
    }
    base.OnModelCreating(modelBuilder);
  }
}